#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define SNAKE_MAXLENGTH 40
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define BLANK_CELL ' '
#define SNAKE_FOOD '$'
#define WALL_CELL '*'

// snake stepping: dy = -1(up), 1(down); dx = -1(left), 1(right), 0(no move)
void snakeMove();
// put a food randomized on a blank cell
void put_money();
// out cells of the grid
void output();
// outs when gameover
int gameover();

char map[12][12]=   // 初始状态，直接打表
    {
        "************",
        "*XXXXH     *",
        "*          *",
        "*          *",
        "*          *",
        "*          *",
        "*          *",
        "*          *",
        "*          *",
        "*          *",
        "*          *",
        "************",
    };

// define vars for snake, notice name of vars in C
int snakeX[SNAKE_MAXLENGTH] = {5, 4, 3, 2, 1}; // 从头到尾的横坐标
int snakeY[SNAKE_MAXLENGTH] = {1, 1, 1, 1, 1}; // 从头到尾的纵坐标
int snakeLength = 5;    // 初始蛇长度

int foodX; // 食物横坐标
int foodY; // 食物纵坐标

int main()
{
    put_money(); // 生成食物
    output();

    
    while(1){
        char destination; // 方向
        scanf(" %c", &destination);
        snakeMove();
        if (destination == 'w') {
            snakeY[0]--;
        }else if (destination == 's') {
            snakeY[0]++;
        }else if (destination == 'a') {
            snakeX[0]--;
        }else if (destination == 'd') {
            snakeX[0]++;
        }

        if (gameover()) {
            printf("GAME OVER!\n");
            break;
        } else {
            // 若吃到食物，则原来的尾位置生成尾部，长度增加，再生成食物；否则记录的尾部位置清零
            if (snakeY[0] == foodY && snakeX[0] == foodX) {
                map[snakeY[snakeLength]][snakeX[snakeLength]] = 'X';
                snakeLength++;
                put_money();
            }else{
                snakeX[snakeLength] = 0;
                snakeY[snakeLength] = 0;
            }

            map[snakeY[0]][snakeX[0]] = 'H'; // 在新的头部生成头
            output();
        }
    }

    return 0;
}

void put_money()
{
    // 在空位置随机生成食物
    srand(time(NULL));
    do{
        foodX = rand() % 9 + 1;
        foodY = rand() % 9 + 1;
    }while(map[foodY][foodX] != ' ');

    map[foodY][foodX] = '$';
}

void output()
{
    for(int i = 0; i < 12; i++){
        for(int j = 0; j < 12; j++){
            printf("%c", map[i][j]);
        }
        printf("\n");
    }
}

void snakeMove()
{   
    // 原来的尾部向前移动了一格，现在变为空
    map[snakeY[snakeLength - 1]][snakeX[snakeLength - 1]] = ' ';
    // 把尾部的坐标保存下来
    snakeX[snakeLength] = snakeX[snakeLength-1];
    snakeY[snakeLength] = snakeY[snakeLength-1];
    // 除了头部全部向前移动一个位置
    for (int i = snakeLength-1; i > 0; i--) {
        snakeX[i] = snakeX[i-1];
        snakeY[i] = snakeY[i-1];
        map[snakeY[i]][snakeX[i]] = 'X';
    }
}

int gameover()
{
    // 当头部撞到边界或者自己的身体时游戏结束
    if (map[snakeY[0]][snakeX[0]] == ' ' || map[snakeY[0]][snakeX[0]] == '$') {
        return 0;
    }
    return 1;
}